package cn.mesmile.thread.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zb
 * @date 2021/5/30 16:19
 * @Description:
 */
@Slf4j
public class AQSTest {

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() ->{
            Thread thread1 = Thread.currentThread();
            log.info(">>>>>>>>>> 开始执行线程：{}", thread1.getName());
            for (;;) {
                log.info(">>>>>>>>>> 【准备阻塞】线程：{}", thread1.getName());
                // 阻塞线程
                LockSupport.park();
                log.info(">>>>>>>>>> 【被唤醒】线程：{}",thread1.getName());
                // 判断一次后，会将【中断标识】擦除
                log.info(">>>>>>>>> 是否中断： {} ", Thread.interrupted());
                log.info("--------------------------------------------------");
            }
        });
        thread.setName("t0");
        thread.start();

        Thread.sleep(2000L);
        log.info(">>>>>>>>>> 【准备唤醒】：{}",thread.getName());
        // 唤醒线程
        LockSupport.unpark(thread);

        Thread.sleep(3000L);
//        Thread.currentThread().interrupt();
        // 中断会将阻塞的线程唤醒
        thread.interrupt();

    }

    public void testOne() throws InterruptedException{
        for (int i = 0; i < 3 ; i++) {
            Thread thread = new Thread(() ->{
                Thread thread1 = Thread.currentThread();
                log.info(">>>>>>>>>> 开始执行线程：{}", thread1.getName());
                for (;;) {
                    log.info(">>>>>>>>>> 【准备阻塞】线程：{}", thread1.getName());
                    // 阻塞线程
                    LockSupport.park();
                    log.info(">>>>>>>>>> 【被唤醒】线程：{}",thread1.getName());
                    log.info("--------------------------------------------------");
                    // 线程被唤醒后退出循环
                    break;
                }
            });
            thread.setName("线程: "+ i);
            thread.start();
            Thread.sleep(2000L);
            log.info(">>>>>>>>>> 【准备唤醒】：{}",thread.getName());
            // 唤醒线程
            LockSupport.unpark(thread);
        }
    }


    public void test(){
        // 创建一个线程计数器，初始化的时候传入线程数量
        CountDownLatch countDownLatch = new CountDownLatch(1);

        new Thread(() ->{
            // 所有线程都【创建完成】才会执行这条语句
            try {
                countDownLatch.await();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();

        // 每执行一次线程就会减去 1
        countDownLatch.countDown();
        // 获取剩余次数
        long count = countDownLatch.getCount();


        // false 为非公平锁   true 为公平锁  默认为 false
        ReentrantLock reentrantLock = new ReentrantLock(false);
        // 加锁
        reentrantLock.lock();
        // 解锁
        reentrantLock.unlock();
    }
}
